package org.flowers.unbeaten.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.flowers.unbeaten.util.DataResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @description 流程模型控制器
 * @author RyanWang
 * @date 2021-08-02 10:40:49
 * @version 1.0
 */
@Api(tags = "流程引擎-流程模型")
@Slf4j
@RestController
@RequestMapping("/process/processModel")
public class ProcessModelController {

    @Autowired
    public TaskService taskService;

    @Autowired
    public RuntimeService runtimeService;

    @Autowired
    public HistoryService historyService;

    @Autowired
    public RepositoryService repositoryService;

    /**
     * 获取流程模型列表数据
     * @return
     */
//    @PostMapping("/list")
//    @ApiOperation("获取流程模型列表")
//    public PageResult list(@RequestBody PageEntity pageEntity) {
//
//        ModelQuery modelQuery = repositoryService.createModelQuery().orderByCreateTime().desc();
//        if (StringUtils.hasText(pageEntity.getSearchKey())) {
//            modelQuery.modelNameLike(pageEntity.getSearchKey());
//        }
//        List<Model> models = modelQuery.listPage(pageEntity.start(), pageEntity.end());
//        List<ProcessModelVo> processModelVoList = new ArrayList<>();
//
//        models.forEach(model -> {
//            ProcessModelVo vo = new ProcessModelVo();
//            vo.setId(model.getId());
//            vo.setDeploymentId(model.getDeploymentId());
//            vo.setName(model.getName());
//            vo.setKey(model.getKey());
//            vo.setVersion(model.getVersion());
//            processModelVoList.add(vo);
//        });
//        // 数据总数
//        long count = modelQuery.list().size();
//
//        return pageResult(processModelVoList, count);
//
//    }

    /**
     * 流程部署
     * @param modelId 设计的流程图模型ID
     * @return
     */
    @PostMapping("/deploy/{modelId}")
    @ApiOperation(value = "流程部署")
    public DataResult deploy(@PathVariable String modelId) {
        try {
            Model model = repositoryService.getModel(modelId);
            byte[] bytes = repositoryService.getModelEditorSource(model.getId());
            if (bytes == null) {
                return DataResult.getResult(-1, "模板数据为空");
            }
            JsonNode modelNode = new ObjectMapper().readTree(bytes);
            BpmnModel bpmnModel = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            Deployment deployment = repositoryService.createDeployment()
                    .name(model.getName())
                    .addBpmnModel(model.getName() + ".bpmn20.xml", bpmnModel)
                    .deploy();
            model.setDeploymentId(deployment.getId());
            repositoryService.saveModel(model);
            log.info(model.getName() + "：流程部署成功");
            return DataResult.getResult(200, "流程部署成功");
        } catch (Exception e) {
            log.error("根据modelId部署流程,异常:{}", e);
            return DataResult.getResult(-1, "流程部署失败");
        }
    }

    /**
     * 根据流程ID删除流程
     * @param ids
     * @return
     */
    @DeleteMapping("/delete/{ids}")
    @ApiOperation(value = "删除流程")
    public DataResult delete(@PathVariable List<String> ids) {
        ids.stream().forEach(modelId -> {
            repositoryService.deleteModel(modelId);
        });
        return DataResult.getResult(200, "流程模型删除成功");
    }

}
